/*
 * Copyright 2011 The Rusted Roof, LLC.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.proteusframework.sample.app;

import org.proteusframework.api.IPluginRegistrar;
import org.proteusframework.api.IProteusApplication;
import org.proteusframework.api.IRuntimeConfiguration;
import org.proteusframework.api.IRuntimeEngine;
import org.proteusframework.api.base.AbstractRuntimeEngine;
import org.proteusframework.api.model.*;
import org.proteusframework.runtime.RuntimeEnvironment;
import org.proteusframework.runtime.StandardProteusApplication;

import java.util.Collection;
import java.util.logging.Logger;

/**
 * @author Tacoma Four
 */
public class SampleApplication extends AbstractRuntimeEngine
{
    private static final Logger logger = Logger.getLogger(SampleApplication.class.getCanonicalName());

    public static void main(String[] args)
    {
        //
        // Let's crank up the logging level to FINEST so we can see what's going on behind the scenes
        //

        /*
        Handler[] handlers = Logger.getLogger("").getHandlers();
        for (Handler handler : handlers)
        {
            handler.setLevel(Level.FINEST);
        }

        LogManager.getLogManager().getLogger("").setLevel(Level.FINEST);
        */


        //
        // Our sample application is content using the standard Proteus application architecture.
        //
        IProteusApplication myApplication = new StandardProteusApplication();


        //
        // Generally, one asks the application for a configuration loader, referring to the application's documentation
        // for detailed information on the format expected by the configuration loader.
        //
        // Our sample application could follow this pattern, using the StandardConfigurationLoader that
        // expects the inputStream to point to a .properties file
        //

        /*
        IConfigurationLoader configLoader = myApplication.createConfigurationLoader();
        File file = new File("/path/to/some.properties");
        InputStream inputStream = new FileInputStream(file);
        IRuntimeConfiguration myRuntimeConfiguration = configLoader.load(inputStream);
        IRuntimeEngine myRuntimeEngine = new SampleApplication(myRuntimeConfiguration);
        */

        //
        // The runtime engine's constructor MUST NOT actually initialize itself because the IPlatformDelegate has yet to
        // be injected into the runtime engine. Instead, configuration and preparing for execution should happen within
        // an override on MyRuntimeEngine.onDelegateInjected()
        //
        IRuntimeEngine myRuntimeEngine = new SampleApplication();

        //
        // The runtime engine, uninitialized, is handed to the application delegate. The application delegate
        // has the responsibility of injecting itself into the runtime engine, indirectly triggering
        // onDelegateInjected() on the myRuntimeEngine-- allowing the engine to initialize itself, but it MUST NOT
        // actually run yet.
        //
        myApplication.setRuntimeEngine(myRuntimeEngine);


        //
        // Finally, with the runtime engine injected into the Proteus Application, the application is ready to be
        // launched.
        //
        myApplication.startApplication();
    }

    public SampleApplication()
    {
        super(RuntimeEnvironment.Desktop);
    }

    public SampleApplication(IRuntimeConfiguration runtimeConfiguration)
    {
        super(RuntimeEnvironment.Desktop, runtimeConfiguration);
    }

    @Override
    protected void onDelegateInjected()
    {
        //
        // Any engine configuration or initialization would take place here - but the application has not formally
        // launched yet.  The application formally launches when the run() method is invoked. This two-step process
        // gives the application the ability to verify that the Proteus Factory Registrar actually has found all
        // of the mandatory Plugin Registrar instances that the application requires to run. If not, it is considered a
        // Proteus Framework best practice for the application to gracefully exit here instead of inside of the run()
        // method.
        //

        try
        {
            IQualifiedName SAMPLEQN = new QualifiedName("sample", "RegistrarFactory");
            IPluginRegistrar pluginRegistrar = delegate.getPluginRegistrar(SAMPLEQN);

            Collection<IVersion> versions = pluginRegistrar.versions();

            for (IVersion version : versions)
                logger.info("Installed Version: " + version.toString());


            /////////////
            //
            // Get Version 1 Interface, default plugin provider
            //
            /////////////

            MyExpectedVersion1Interface example1 = (MyExpectedVersion1Interface)
                    pluginRegistrar.createPlugin(new Version(1), MyExpectedVersion1Interface.class);

            logger.info("Example 1: " + example1.doCalculation(23));


            /////////////
            //
            // Get Version 1 Registrar, Version 1 Interface
            //
            /////////////

            IVersionDescriptor versionDescriptorA =
                    new VersionDescriptor(new QualifiedName("sample", "SamplePluginV1Registrar"), new Version(1, 0));


            MyExpectedVersion1Interface example2 = pluginRegistrar.createPlugin(versionDescriptorA, MyExpectedVersion1Interface.class);
            logger.info("Example 2: " + example2.doCalculation(23));

            /////////////
            //
            // Get Version 2 Registrar, Version 1 Interface
            // Registrar offers a backwards compatible implementation, albeit with a different calculation formula
            //
            /////////////

            IVersionDescriptor versionDescriptorB =
                    new VersionDescriptor(new QualifiedName("sample", "SamplePluginV2Registrar"), new Version(1));


            MyExpectedVersion1Interface example3 = pluginRegistrar.createPlugin(versionDescriptorB, MyExpectedVersion1Interface.class);
            logger.info("Example 3: " + example3.doCalculation(23));

            /////////////
            //
            // Get Version 2 Registrar, Version 2 Interface
            //
            /////////////

            IVersionDescriptor versionDescriptorC =
                    new VersionDescriptor(new QualifiedName("sample", "SamplePluginV2Registrar"), new Version(2, 0));

            MyExpectedVersion2Interface example4 = pluginRegistrar.createPlugin(versionDescriptorC, MyExpectedVersion2Interface.class);
            logger.info("Example 4: " + example4.doCalculation(23));
            logger.info("Even Check: " + example4.isEven(23));

        } catch (NoSuchQualifiedNameException e)
        {
            e.printStackTrace();
        } catch (NoSuchVersionException e)
        {
            e.printStackTrace();
        }

    }

    @Override
    public void run()
    {
        logger.info("The application would formally launch here in the run() method");
    }
}
